package com.chatroomdemo.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class TestWebSocketController extends TextWebSocketHandler {
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //这个方法会在websocket连接建立之后，自动调用
        System.out.println("TestSocket 连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //websocket收到消息时自动调用
        System.out.println("TestSocket 收到消息" + message.toString());
        //session是个会话，记录了通信双方是谁
        session.sendMessage(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //连接异常时自动调用
        System.out.println("TestSocket 连接异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //连接正常关闭后，自动调用
        System.out.println("Test Socket 连接正常关闭");
    }
}
